<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="./lib/d3.js"></script>
</head>

<body>
    <div id="svg"></div>
    <script>
        const dataset = [50, 43, 120, 87, 99, 167, 142];
        const height = 400;
        const width = 400;
        const svg = d3.select("#svg").append("svg").attr("width", width).attr("height", height);
        const padding = { top: 20, right: 20, bottom: 20, left: 20 };
        const rectStep = 35;
        const rectWidth = 30;
        const genBar = obj => obj.attr("fill", "#000")
            .attr("x", (d, i) => padding.left + i * rectStep)
            .attr("y", (d, i) => height - padding.bottom - d)
            .attr("width", rectWidth)
            .attr("height", d => d);
        const genText = obj => obj.attr("fill", "#fff")
            .attr("font-size", "14px").attr("text-anchor", "middle")
            .attr("x", (d, i) => padding.left + i * rectStep)
            .attr("y", (d, i) => height - padding.bottom - d)
            .attr("dx", rectWidth / 2)
            .attr("dy", "1em").text(d => d);
        const draw = dataset => {
            const updateRect = svg.selectAll("rect").data(dataset);
            const updateText = svg.selectAll("text").data(dataset);
            //更新旧数据
            genBar(updateRect);
            //进入的新数据
            genBar(updateRect.enter().append("rect"));
            //移除无效
            updateRect.exit().remove();

            genText(updateText);
            genText(updateText.enter().append("text"));
            updateText.exit().remove();
        };
        draw([50, 43, 120, 87, 99, 167, 142]);
        setTimeout(() => {
            draw([50, 43, 120, 87, 99, 167, 100]);
        }, 2000);
    </script>
</body>

</html>
